package com.jiubodou.myoauth2.controller;

import com.alibaba.fastjson2.JSON;
import com.jiubodou.myoauth2.oauth2class.my.MyAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.HashSet;

/**
 * @ClassName MyController
 * @Description
 * @Author huyingliang
 * @Date 2023/5/4 16:44
 */
@RestController
@RequestMapping("/oauth")
public class MyController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @PostMapping("/login")
    public String login() throws HttpRequestMethodNotSupportedException {
        /*假设接收到的参数是 username：17605187510
         * password:123456  最终的目的是 根据 username 查询到一个 LQQS 的数据，并生成token*/

        HashSet<SimpleGrantedAuthority> simpleGrantedAuthorities = new HashSet<>();
        simpleGrantedAuthorities.add(new SimpleGrantedAuthority("user"));

        MyAuthenticationToken myAuthenticationToken = new MyAuthenticationToken("17605187510", "123456",
                simpleGrantedAuthorities);/*这里使用三个参数的构造方法（是为了让其Authenticated字段成为true），但是实际上这个用户根本就没有认证过
                用户还没查找，密码还没校验，client也没有校验，怎么会是认证过的呢？但是框架的代码中必须要认证过的用户这一步才能走通，所以这里只能让其是认证过的*/
        HashMap<String, String> parameters = new HashMap<>();
        myAuthenticationToken.setDetails(parameters);
        myAuthenticationToken.setClientId("lqqs");

        parameters.put("grant_type", "my_grant_type");
        parameters.put("username", "17605187510");
        parameters.put("password", "123456");

        ResponseEntity<OAuth2AccessToken> postedAccessToken = tokenEndpoint.postAccessToken(myAuthenticationToken,
                parameters);

        return JSON.toJSONString(postedAccessToken);


    }

}
